package com.wang.controller;

import com.wang.entity.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @Classname UploadController
 * @Description TODO
 * @Date 2024/5/15 9:45
 * @Created by pc
 */
@Controller
public class UploadController {

    // 获取配置文件中的上传目录的路径
    @Value("${uploadFolder}")
    private String uploadFolder;

    @RequestMapping("/picUpload")
    public String picUpload(){
        return "picUpload";
    }

    @RequestMapping("/picUpload2")
    public String picUpload2(){
        return "multiUpload";
    }

    @ResponseBody
    @PostMapping("/upload")
    public Object upload(MultipartFile fileUpload){
        try {
            // 获取文件名
            String fileName = fileUpload.getOriginalFilename();
            // 根据文件名截取后缀  后面的文件名是uuid+后缀
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffixName;
            File uploadFolderFile = new File(uploadFolder);
            if(!uploadFolderFile.exists()){
                uploadFolderFile.mkdirs();
            }
            // E:/upload/xwakfjfsdkf.jsp
            File file = new File(uploadFolder + fileName);
            fileUpload.transferTo(file);
            return new Message(0,"上传成功");

        } catch (Exception e) {
            e.printStackTrace();
            return new Message(-1,"上传失败");
        }
    }

    // 多文件上传
    @ResponseBody
    @RequestMapping("/uploadMultifile")
    // RequestParam 注解除了解决前后端传递k不同之外 还可以用于多文件上传
    public Object upload2(@RequestParam("attachment") MultipartFile [] attachment){
        try {
            File uploadFolderFile = new File(uploadFolder);
            if(!uploadFolderFile.exists()){
                uploadFolderFile.mkdirs();
            }
            for (MultipartFile file : attachment) {
                String fileName = file.getOriginalFilename();
                File dest = new File(uploadFolderFile + fileName);
                file.transferTo(dest);
            }
            return new Message(0,"上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Message(-1,"上传失败");
        }
    }
}
